package com.kuang.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.kuang.mapper.UserMapper;
import com.kuang.pojo.User;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;

@Component
public class TokenUtils {
    private static UserMapper staticUserMapper;
    @Autowired
    UserMapper userMapper;
    @PostConstruct
    public void setUserService(){
        staticUserMapper = userMapper;
    }
    //创建token
    public static String createToken(String userId,String sign){
        // 获取当前时间
        Date currentDate = new Date();
        // 创建Calendar实例
        Calendar calendar = Calendar.getInstance();
        // 设置Calendar的时间为currentDate
        calendar.setTime(currentDate);
        // 向前偏移两个小时
        calendar.add(Calendar.HOUR_OF_DAY, 2);
        // 获取偏移后的时间
        Date offsetDate = calendar.getTime();
        return JWT.create().withAudience(userId)//将userId保存到token里
                .withExpiresAt(offsetDate)      //2小时候token过期
                .sign(Algorithm.HMAC256(sign)); //将password作为token密钥
    }
    //获取当前登录的用户信息
    public static User getCurrentUser(){
        //获取当前请求的HttpServletRequest对象，这样就能在下面访问请求头、参数等
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes())
                .getRequest();
        try {
            //从请求头里获取token
            String token = request.getHeader("token");
            //如果token不为空，则从Audience中获取第一个数据(是用户的id)
            if (StringUtils.isNotBlank(token)){
                String userId = JWT.decode(token).getAudience().get(0);
                return staticUserMapper.selectUserById(Integer.parseInt(userId));
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}
